package com.hcb.tonguetiphealth.adapter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader.ImageCallBack;
import com.hcb.tonguetiphealth.model.CityActivity;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.view.MemberHomepageActivity;
import com.hcb.tonguetiphealth.view.R;

public class CityWideActivitysListAdapter extends BaseAdapter {

	private Context mContext;
	private List<CityActivity> mList;
	private LayoutInflater vi;
	private AsyncBitmapLoader asyncBitmapLoader;
	private Activity ctx;
	private Handler mHandler;
	private Dialog waitDialog;
	private int topCount;
	private int topCityActivityListSize;
	
	public CityWideActivitysListAdapter(Context context,List<CityActivity> list, Handler mHandler) {
		mContext = context;
		ctx = (Activity)context;
		mList = list;
		asyncBitmapLoader = AsyncBitmapLoader.getInstance();
		this.mHandler = mHandler;
	}
	
	public int getCount() {
		if(mList == null) {
			return 0;
		}
		return mList.size();
	}
	
	public Object getItem(int position) {
		if(mList == null) {
			return null;
		} else {
			return mList.get(position);
		}
	}
	
	public long getItemId(int position) {
		return position;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {

		View view;
		
		if(convertView == null) {
			vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = (LinearLayout) vi.inflate(R.layout.city_wide_list_item, null);
		} else {
			view = convertView;
		}
		FillDataIntoView(view, position);
		
		return view;
	}
	
	
	private void FillDataIntoView(View view,final int position) {
		final CityActivity cityActivity = mList.get(position);

		ImageView img = (ImageView)view.findViewById(R.id.city_wide_usr_img);
		TextView tvName = (TextView)view.findViewById(R.id.city_wide_name_tv);
		TextView tvType = (TextView)view.findViewById(R.id.activity_type_tv);
		TextView tvAddTime = (TextView)view.findViewById(R.id.activity_write_time);
		
		TextView tvActivityName = (TextView)view.findViewById(R.id.activity_name_tv);
		TextView tvActivityAddress = (TextView)view.findViewById(R.id.activity_address_tv);
		final TextView tvActivityIntro = (TextView)view.findViewById(R.id.city_wide_intro_tv);
		//LinearLayout llContent = (LinearLayout)view.findViewById(R.id.city_wide_intro_ll);
		final TextView tvPeopleNum = (TextView)view.findViewById(R.id.activity_peoplenum_tv);
		Button btAttentd = (Button)view.findViewById(R.id.city_wide_attend_button);
		//final ImageView imgUporDown = (ImageView)view.findViewById(R.id.city_wide_intro_upordown);
		final LinearLayout llTitle = (LinearLayout)view.findViewById(R.id.city_wide_linearlayout);
		final LinearLayout llInfo = (LinearLayout)view.findViewById(R.id.city_wide_info_linearlayout);
		final ImageView infoImgUporDown = (ImageView)view.findViewById(R.id.upordown_img);
		final User user = cityActivity.getUser();
		
		tvName.setText(user.getUserName());
		int type = cityActivity.getType();
		if(type == 1) {
			tvType.setText("商家");
		} else if(type == 2) {
			tvType.setText("个人");
		}
		
		tvActivityName.setText(cityActivity.getActivityName());
		tvActivityAddress.setText(cityActivity.getActivityAddress());
		tvAddTime.setText(cityActivity.getAddTime());
		tvActivityIntro.setText("    " + cityActivity.getActivityIntro());
		tvPeopleNum.setText(cityActivity.getPeopleNum()+" 人");
		
		if(cityActivity.isOpen()) {
			llInfo.setVisibility(View.VISIBLE);
		} else {
			llInfo.setVisibility(View.GONE);
		}
		if(cityActivity.isTop()) {
			infoImgUporDown.setBackgroundResource(R.drawable.search_red);
		} else {
			if(cityActivity.isOpen()) {
				infoImgUporDown.setBackgroundResource(R.drawable.list_more_up);
			} else {
				infoImgUporDown.setBackgroundResource(R.drawable.list_more);
			}
		}
		llTitle.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(position < topCount) {
					mHandler.sendEmptyMessage(MessageWhat.CANCEL_TIMER);
					showInfoDialog(cityActivity);
				} else {
					if (llInfo.getVisibility()==View.GONE || llInfo.getVisibility() == View.INVISIBLE) {
						llInfo.setVisibility(View.VISIBLE);
						cityActivity.setOpen(true);
						infoImgUporDown.setBackgroundResource(R.drawable.list_more_up);
					} else {
						llInfo.setVisibility(View.GONE);
						cityActivity.setOpen(false);
						infoImgUporDown.setBackgroundResource(R.drawable.list_more);
					}
				}
			}
		});
		
		/*llContent.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (tvActivityIntro.getVisibility() == View.GONE || tvActivityIntro.getVisibility() == View.INVISIBLE) {
					tvActivityIntro.setVisibility(View.VISIBLE);
					imgUporDown.setBackgroundResource(R.drawable.close_more);
				}else {
					tvActivityIntro.setVisibility(View.GONE);
					imgUporDown.setBackgroundResource(R.drawable.open_more);
				}
			}
			
			
		});*/
		
		img.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			 Intent intent = new Intent(ctx,MemberHomepageActivity.class);
			 Bundle bundle = new Bundle();
			 bundle.putSerializable("memeber", user);
			 intent.putExtra("fromWidget", "CityWideActivitysListAdapter");
			 intent.putExtras(bundle);
			 ctx.startActivity(intent);
			}
		});
		
		btAttentd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Global.user == null) {
					Toast.makeText(mContext, "请登录", Toast.LENGTH_LONG).show();
					mHandler.sendEmptyMessage(MessageWhat.LOGIN);
				}else {
					commmitAttend(cityActivity.getId(), cityActivity);
					String msg = "尊敬的"+Global.user.getUserName()+",您好！"+"欢迎参加由"+
								 user.getUserName() +"发起的活动:"+cityActivity.getActivityName()+
								 "  地址:"+cityActivity.getActivityAddress()+
								 "  此短信作为参与活动凭证！请妥善保管！"+
								 " 【舌尖健康】";
					sendMessage(msg);
					atentionMember(user.getUserId());
//					Intent intent = new Intent();
//					intent.setClass(ctx, ChatActivity.class);
//					intent.putExtra("user", user);
//					intent.putExtra("from", "user");
//					ctx.startActivity(intent);
				}
			}
		});
		
		String imageURL = user.getImgUrl();
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(img, imageURL, new ImageCallBack() {  
              
            public void imageLoad(ImageView imageView, Bitmap bitmap) {  
                // TODO Auto-generated method stub  
                imageView.setImageBitmap(bitmap);  
            }  
        });  
		if(bitmap == null) {    
			img.setImageResource(R.drawable.ic_launcher);    
		} else {    
		    img.setImageBitmap(bitmap);    
		}
	    
	}
	private void commmitAttend(final String id,final CityActivity activity){
		
		new Thread(){
			public void run() {
				List<NameValuePair>params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("id", id));
				String response = HttpUtils.Post(Global.getServletpeoplenum(), params);
				if (Global.DEBUG) {
					System.out.println("提交参与返回信息"+response);
				}
				if (response!=null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strRrturn = jsonObject.getString("return");
						if("true".equals(strRrturn)){
							activity.setPeopleNum(activity.getPeopleNum()+1);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}	
			}
		}.start();
	}
	
	private void sendMessage(final String msg){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List<NameValuePair>params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userid", Global.user.getUserId()));
				params.add(new BasicNameValuePair("message", msg));
				String response = HttpUtils.Post1(Global.getServletactivitysendmsg(), params);
				if (Global.DEBUG) {
					System.out.println("提交参与返回信息"+response);
				}
				String reqSucess = "false";
				if (response!=null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strRrturn = jsonObject.getString("return");
						if("true".equals(strRrturn)){
							reqSucess = "true";
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				Message message = new Message();
				message.what = MessageWhat.DIMISS_DIALOG;
				message.obj = reqSucess;
				mHandler.sendMessage(message);
			}
		}.start();
	}
	
	private void atentionMember(final String userid){
			new Thread(){
				public void run() {
					List<NameValuePair>params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("memberUserId", userid));
					params.add(new BasicNameValuePair("myUserid", Global.user.getUserId()));
					String response = HttpUtils.Post(Global.getServletattentoin(), params);
					if (response!=null) {
						try {
							JSONObject jsonObject = new JSONObject(response);
							String strReturn = jsonObject.getString("return");
							if ("true".equals(strReturn)) {
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} 
				}
			}.start();
		}
	private void showInfoDialog(final CityActivity cityActivity) {
    	waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.activity_info_dialog);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 1.0f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
    	
	    ImageView img = (ImageView)waitDialog.findViewById(R.id.city_wide_usr_img);
		TextView tvName = (TextView)waitDialog.findViewById(R.id.city_wide_name_tv);
		TextView tvType = (TextView)waitDialog.findViewById(R.id.activity_type_tv);
		TextView tvAddTime = (TextView)waitDialog.findViewById(R.id.activity_write_time);
		
		TextView tvActivityName = (TextView)waitDialog.findViewById(R.id.activity_name_tv);
		TextView tvActivityAddress = (TextView)waitDialog.findViewById(R.id.activity_address_tv);
		final TextView tvActivityIntro = (TextView)waitDialog.findViewById(R.id.city_wide_intro_tv);
		//LinearLayout llContent = (LinearLayout)view.findViewById(R.id.city_wide_intro_ll);
		final TextView tvPeopleNum = (TextView)waitDialog.findViewById(R.id.activity_peoplenum_tv);
		Button btAttentd = (Button)waitDialog.findViewById(R.id.city_wide_attend_button);
		//final ImageView imgUporDown = (ImageView)view.findViewById(R.id.city_wide_intro_upordown);
		/*final LinearLayout llTitle = (LinearLayout)view.findViewById(R.id.city_wide_linearlayout);
		final LinearLayout llInfo = (LinearLayout)view.findViewById(R.id.city_wide_info_linearlayout);
		final ImageView infoImgUporDown = (ImageView)view.findViewById(R.id.upordown_img);*/
		final User user = cityActivity.getUser();
		
		tvName.setText(user.getUserName());
		int type = cityActivity.getType();
		if(type == 1) {
			tvType.setText("商家");
		} else if(type == 2) {
			tvType.setText("个人");
		}
		
		tvActivityName.setText(cityActivity.getActivityName());
		tvActivityAddress.setText(cityActivity.getActivityAddress());
		tvAddTime.setText(cityActivity.getAddTime());
		tvActivityIntro.setText("    " + cityActivity.getActivityIntro());
		tvPeopleNum.setText(cityActivity.getPeopleNum()+" 人");
		btAttentd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Global.user == null) {
					Toast.makeText(mContext, "请登录", Toast.LENGTH_LONG).show();
					mHandler.sendEmptyMessage(MessageWhat.LOGIN);
				} else {
					commmitAttend(cityActivity.getId(), cityActivity);
					String msg = "尊敬的"+Global.user.getUserName()+",您好！"+"欢迎参加由"+
								 user.getUserName() +"发起的活动:"+cityActivity.getActivityName()+
								 "  地址:"+cityActivity.getActivityAddress()+
								 "  此短信作为参与活动凭证！请妥善保管！"+
								 " 【舌尖健康】";
					sendMessage(msg);
					atentionMember(user.getUserId());
				}
			}
		});
		String imageURL = user.getImgUrl();
        Bitmap bitmap = asyncBitmapLoader.loadBitmap(img, imageURL, new ImageCallBack() {  
              
            public void imageLoad(ImageView imageView, Bitmap bitmap) {  
                // TODO Auto-generated method stub  
                imageView.setImageBitmap(bitmap);  
            }  
        });  
		if(bitmap == null) {    
			img.setImageResource(R.drawable.ic_launcher);    
		} else {    
		    img.setImageBitmap(bitmap);    
		}
	    waitDialog.setCancelable(true);
	    waitDialog.setCanceledOnTouchOutside(true);
	    waitDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				if(topCityActivityListSize > 3) {
					mHandler.sendEmptyMessage(MessageWhat.START_TIMER);
				}
			}
		});
    	waitDialog.show();
	}

	public void setTopCityActivityListSize(int topCityActivityListSize) {
		this.topCityActivityListSize = topCityActivityListSize;
		if(topCityActivityListSize > 3) {
			topCount = 3;
		} else {
			topCount = topCityActivityListSize;
		}
	}
}
